package com.itclass.auth.handler.authorize;

import cn.hutool.json.JSONUtil;
import com.itclass.auth.enums.ResultCodeEnum;
import com.itclass.auth.pojo.db.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足处理器
 */
@Slf4j
public class AuthorizeAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        log.warn("权限不足");
        // 设置响应内容类型为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 设置响应字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        // 创建一个包含错误信息的 JSON 对象
        String json = JSONUtil.toJsonStr(Result.fail(ResultCodeEnum.PERMISSION).message("权限不足"));
        response.getWriter().write(json);
    }
}
